<template>
  <GlobalHeader/>
  <div class="user-profile-page">
    <el-row :gutter="20">
      <el-col :span="6" class="aside">
        <el-card class="profile-card">
          <div class="user-info-display">
            <div v-if="userInfo.id">
              <el-avatar :size="80" :src="userInfo.userAvatar || defaultAvatar" />
              <div class="username">{{ userInfo.userName || '用户' + userInfo.id }}</div>
              <div class="user-id">ID: {{ userInfo.id }}</div>
              <div class="user-profile-text">{{ userInfo.userProfile || '这个人很懒，什么都没写...' }}</div>
            </div>

            <div v-else>
              正在加载用户数据...
            </div>

            <el-button
                type="primary"
                size="small"
                text
                @click="isEditing = true"
                class="edit-profile-btn"
            >
              <el-icon><Edit /></el-icon>
              <span>编辑资料</span>
            </el-button>
          </div>
        </el-card>

        <el-card class="stats-card mt-4">
          <template #header>
            <div class="card-header">
              <span>数据总览</span>
            </div>
          </template>
          <div class="stat-item">
            <span class="stat-label">已通过题目数</span>
            <span class="stat-value text-green">{{ stats?.acProblemNum ?? 0}}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">尝试题目数</span>
            <span class="stat-value">{{ stats?.submitProblemNum ?? 0}}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">通过率</span>
            <span class="stat-value">{{
                stats?.submitProblemNum ?? 0 > 0
                    ? (((stats?.acProblemNum ?? 0)/ (stats?.submitProblemNum ?? 1)) * 100).toFixed(2) + '%'
                    : '0.00%'
              }}</span>
          </div>
        </el-card>

        <el-card class="stats-card mt-4">
          <template #header>
            <div class="card-header">
              <span>语言</span>
            </div>
          </template>

          <div
              v-for="stat in languageStats"
              :key="stat.language"
              class="stat-item"
          >
            <span class="stat-label">{{ stat.language }}</span>

            <span class="stat-value text-green">{{ stat.passNum }}</span>
          </div>

          <div v-if="!languageStats.length" class="empty-state">
            暂无数据
          </div>
        </el-card>
      </el-col>

      <el-col :span="18" class="main-content">
        <UserSettings
            v-if="isEditing"
            :initial-data="userInfo"
            @update-success="handleUpdateSuccess"
            @cancel-edit="isEditing = false"
        />

        <el-tabs v-else v-model="activeTab" class="profile-tabs">
          <el-tab-pane label="通过记录" name="accepted">
            <AcceptedQuestions/>
          </el-tab-pane>
          <el-tab-pane label="提交历史" name="submissions">
            <SubmissionHistory/>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useUserStore } from '../../stores/user.ts';
import { ElMessage } from 'element-plus';
import UserSettings from "../../view/user/UserSettings.vue";
import AcceptedQuestions from "../../view/user/AcceptedQuestions.vue";
import { Edit } from '@element-plus/icons-vue';
import SubmissionHistory from "../../view/user/SubmissionHistory.vue";
import GlobalHeader from "../../components/GlobalHeader.vue";
import {
  type QuestionDoStatusVO, type QuestionLanguageStatus,
  QuestionSubmitControllerService,
  type UserVO
} from "../../../generated";

const userStore = useUserStore();
const activeTab = ref('accepted');
const userInfo = ref<UserVO>({}); // 或者 const userInfo = ref({});
const defaultAvatar = 'http://t3jtjn58z.hd-bkt.clouddn.com/OIP.jpg'; // 默认头像

// ⭐️ 新增状态：控制右侧内容显示 Tab 还是编辑表单
const isEditing = ref(false);

// ... (stats 和 acceptedQuestions 模拟数据保持不变) ...
const stats = ref<QuestionDoStatusVO>({
  acProblemNum: 0,
  submitProblemNum: 0,
});

const languageStats  = ref<QuestionLanguageStatus[]>([]);
const loadData = async () => {
  // 从 Pinia store 中获取用户信息，这里假定 store 中已经有数据
  // 如果 store 也是异步的，你需要确保在 store 加载完毕后再调用此函数
  userInfo.value = userStore.user;

  try {
    const res = await QuestionSubmitControllerService.questionDoStatus();
    if (res.code === 0 && res.data) {
      stats.value = res.data;
    } else {
      console.error("获取用户做题状态失败", res.message);
    }
  } catch (error) {
    console.error("请求发生错误", error);
  }
  try {
    const res = await QuestionSubmitControllerService.questionLanguageStatus();
    if (res.code === 0 && res.data) {
      // res.data 是一个数组，直接赋值给 ref 的 .value
      languageStats.value = res.data;
    } else {
      console.error("获取语言状态失败", res.message);
    }
  } catch (error) {
    console.error("请求发生错误", error);
  }
};

// 资料修改成功后的回调
const handleUpdateSuccess = (newInfo: any) => {
  // 1. 更新本地显示的用户信息
  userInfo.value = { ...userInfo.value, ...newInfo };
  ElMessage.success('个人资料更新成功！');
  // 2. ⭐️ 退出编辑模式，返回 Tab 视图
  isEditing.value = false;
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.user-profile-page {
  max-width: 1200px;
  margin: 20px auto;
}

/* --- 左侧卡片样式 --- */
.aside {
  padding-top: 0;
}

.profile-card {
  text-align: center;
}

.user-info-display {
  padding: 10px 0;
}

.username {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
  color: #333;
}

.user-id {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.user-profile-text {
  font-size: 14px;
  color: #666;
  padding: 10px;
  background-color: #f7f7f7;
  border-radius: 4px;
  line-height: 1.6;
  margin-top: 15px;
}

/* --- 数据统计卡片样式 (扩展功能) --- */
.stats-card .card-header {
  font-weight: bold;
  color: #333;
  font-size: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-value {
  font-weight: bold;
  font-size: 15px;
}

.text-green {
  color: #00b38a; /* LeetCode 风格的绿色 */
}

/* --- 右侧主要内容样式 --- */
.profile-tabs ::v-deep(.el-tabs__nav-wrap::after) {
  background-color: transparent; /* 隐藏 El-Tabs 默认底线 */
}

.mt-4 {
  margin-top: 20px;
}
</style>